-- UIBuyScrap
-- Created by huanghr
-- 购买冈布奥碎片界面

UIBuyScrap = class("UIBuyScrap", function()
    return cc.Layer:create();
end);

function UIBuyScrap.create(goodsId, priceType)
    return UIBuyScrap.new(goodsId, priceType);
end

-- 内部函数声明
local resize;
local MARKET_OPEN = 1;

-- 构造函数
function UIBuyScrap:ctor(goodsId, priceType)
    self:setName("UIBuyScrap");
    self.goodsId = goodsId;

    -- 初始化
    local node = cc.CSLoader:createNode("layout/item/BuyFood.csb");
    self:addChild(node);
    self.node = node;

    self.priceType = priceType;

    if DungeonM.isInDungeon() and not DungeonM.isPause() then
        -- 迷宫中层级要调高
        self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 11);
    end

    -- 更换背景底图
    local up1 = findChildByName(self.node, "CT/bg_type");
    local up2 = findChildByName(self.node, "CT/bg_type2")
    up1:loadTexture(getTitleBgIconPath("pet"));
    up2:loadTexture(getTitleBgIconPath("pet"))
    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册各种点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 注册点击事件
function UIBuyScrap:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIBuyScrap");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 购买个数
    local str = getLocStr("bulk_purchase");
    local dbase = MarketM.query(self.goodsId, "dbase") or {};
    if self.priceType == MARKET_OPEN and dbase["activity_id"] then
        local goodsInfo = MarketM.query(self.goodsId);
        local attrib = table.keys(goodsInfo["price"])[1];
        if type(attrib) == "number" then
            str = getLocStr("btn_text_exchange_multi");
        end
    end
    -- 注册确认购买按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/price1_btn");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 尝试购买
            self:tryBuy(10);
        end
    end
    btnBuy:addTouchEventListener(onBuyClick);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuy:setTitleText(string.format(str, 10));

    -- 注册确认购买按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/price2_btn");
    local function onBuyClick2(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 尝试购买
            self:tryBuy(1);
        end
    end
    btnBuy:addTouchEventListener(onBuyClick2);
    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuy:setTitleText(string.format(str, 1));
end

-- 注册事件处理回调函数
function UIBuyScrap:registerEventCallback()
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            EventMgr.removeAll("UIBuyScrap");
            local uiForm2 = UIMgr.getCurrentScene():getFormByName("UIScrapMarket");
            if uiForm2 then
                uiForm2:redraw();
            end
        elseif ev == "enter" then
            local dbase = MarketM.query(self.goodsId, "dbase") or {};
            if self.priceType == MARKET_OPEN and dbase["activity_id"] then
                local goodsInfo = MarketM.query(self.goodsId);
                local attrib = table.keys(goodsInfo["price"])[1];
                if type(attrib) == "number" then
                    -- 显示活动兑换的货币信息
                    local uiTopMenu = UIMgr:getCurrentScene().topMenu;
                    uiTopMenu:setExchangeCurrency(attrib);
                    uiTopMenu:show(TOPMENU_FRAME_ACTIVITY_EXCHANGE, TOPMENU_FRAME_GEM);
                end
            end
        end
    end);
    EventMgr.register("UIBuyScrap", event.BUY_SLIME_SCRAP, function(args)
        self:redraw();

        local lightNode2 = findChildByName(self.node, "CT/item/bg");
        lightNode2:removeAllChildren();

        if type(args.amount) == "number" and args.amount > 1 then
            playEffect(lightNode2, 1231, 93, 9,  nil, 0.82);
        else
            playEffect(lightNode2, 1180, 93, 9,  nil, 0.82);
        end
    end);
end

-- 重绘
function UIBuyScrap:redraw()
    local goodsInfo;
    local itemId;
    local price;
    local attrib;
    local value;
    if "SkyPetShop" == self.priceType then
        goodsInfo = SkyPetShopM.query(self.goodsId);
        itemId = goodsInfo.sell_scrap[2];
        price = goodsInfo["scrap_price"];
        attrib = price[2];
        value = price[3];
    else
        -- 获取商品信息
        goodsInfo = MarketM.getGoodsInfo(self.goodsId);
        local bonusInfo = goodsInfo["bonus"];
        itemId = bonusInfo[1][2];

        attrib = table.keys(goodsInfo["price"])[1];
        value  = table.values(goodsInfo["price"])[1];
    end

    -- 显示商品名称
    local CT = findChildByName(self.node, "CT");

    local nameLabel = CT:getChildByName("title");
    local subHeadLabel = findChildByName(self.node, "CT/subhead");

    nameLabel:setString(ItemM.query(itemId, "name"));
    TextStyleM.setTitleStyle(nameLabel);

    -- 当前拥有的数量
    -- local itemAmount = ItemM.getAmount(ME.user, itemId);
    -- TextStyleM.setSubheadStyle(subHeadLabel);
        -- 先停止滚动
    if self.scrollingData and self.scrollingData.classId ~= itemId then
        stopScrolling(subHeadLabel);
    end

    -- 当前拥有的数量
    TextStyleM.setSubheadStyle(subHeadLabel);
    local curAmount = ItemM.getAmount(ME.user, itemId);
    local scrollingData = self.scrollingData;

    local str = getLocStr("own_num");
    local dbase = MarketM.query(self.goodsId, "dbase") or {};
    if self.priceType == MARKET_OPEN and dbase["activity_id"] then
        -- 活动的
        local remainTime = 0;
        if type(dbase["activity_id"]) == "table" then
            local activityId = ActivityDungeonM.getCurrentActivityId();
            if table.indexOf(dbase["activity_id"], activityId) >= 0 then
                remainTime = ActivityM.getRemainRunningTime(activityId);
            end
        else
            remainTime = ActivityM.getRemainRunningTime(dbase["activity_id"]);
        end
        str = str .. string.format(getLocStr("activity_scrap_time"), remainingTimeDesc(remainTime));
        self:tickTime(itemId);
    end

    -- 没有滚动过
    if not scrollingData or scrollingData.classId ~= itemId then
        subHeadLabel:setString(string.format(str, ItemM.getAmount(ME.user, itemId)));
        self.scrollingData = {
            ["lastAmount"] = curAmount,
            ["classId"]    = itemId,
        };
    else
        -- 滚动
        numScrolling(subHeadLabel, str, scrollingData.lastAmount, curAmount, 30);

        scrollingData.lastAmount = curAmount;
    end

    -- 显示商品价格
    local priceNode1 = findChildByName(self.node, "CT/price1");
    local priceNode2 = findChildByName(self.node, "CT/price2");

    local priceLabel1 = findChildByName(priceNode1, "price_label");

    TextStyleM.setTextStyle(priceLabel1, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    priceLabel1:setString(tostring(value * 10));

    -- 购买一个时的价格
    local priceLabel2 = findChildByName(priceNode2, "price_label");

    TextStyleM.setTextStyle(priceLabel2, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    priceLabel2:setString(tostring(value));

    -- 获取金钱
    -- 获取当前用户的金币数量
    local btnBuy1 = findChildByName(self.node, "CT/price1_btn");
    local btnBuy2 = findChildByName(self.node, "CT/price2_btn");

    local needAmount;

    if "SkyPetShop" == self.priceType then
        needAmount = ItemM.getAmount(ME.user, attrib);
    elseif type(attrib) == "number" then
        needAmount = ItemM.getAmount(ME.user, attrib);
    else
        needAmount = ME.user:queryAttrib(attrib);
    end

    if needAmount >= value*10 then
        TextStyleM.setTextStyle(priceLabel1, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btnBuy1:setBright(true);
        btnBuy1:setTouchEnabled(true);
    else
        TextStyleM.setTextStyle(priceLabel1, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_RED, true);
        btnBuy1:setBright(false);
        btnBuy1:setTouchEnabled(false);
    end

    if needAmount >= value then
        TextStyleM.setTextStyle(priceLabel2, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btnBuy2:setBright(true);
        btnBuy2:setTouchEnabled(true);
    else
        TextStyleM.setTextStyle(priceLabel2, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_RED, true);
        btnBuy2:setBright(false);
        btnBuy2:setTouchEnabled(false);
    end

    -- 显示价格对应的背景
    local priceBg2 = findChildByName(priceNode2, "price_bg");
    local priceBg1 = findChildByName(priceNode1, "price_bg");

    local gemBg1 = findChildByName(priceNode1, "gem_bg");
    local gemBg2 = findChildByName(priceNode2, "gem_bg");
    local itemIcon1 = findChildByName(self.node, "CT/item_icon");
    local itemIcon2 = findChildByName(self.node, "CT/item_icon2");

    if "SkyPetShop" == self.priceType then
        priceBg1:setVisible(false);
        priceBg2:setVisible(false);

        gemBg1:setVisible(true);
        gemBg2:setVisible(true);

        itemIcon1:setVisible(true);
        itemIcon2:setVisible(true);
        itemIcon1:setScale(0.7);
        itemIcon2:setScale(0.7);
        local icon = ItemM.query(attrib, "icon");
        local iconPath = getItemIconPath(icon);

        itemIcon2:loadTexture(iconPath);
        itemIcon1:loadTexture(iconPath);
    else
        priceBg1:setVisible(false);
        priceBg2:setVisible(false);

        gemBg1:setVisible(true);
        gemBg2:setVisible(true);

        if type(attrib) == "number" then
            -- TODO 以后进行一次统一修改，目前暂时只有红包，用红包底
            gemBg1:loadTexture(getUIMarketIconPath("red_bag"));
            gemBg2:loadTexture(getUIMarketIconPath("red_bag"));
        end
    end

    --
    local item = findChildByName(self.node, "CT/item");

    -- 物品图标
    local iconImg = findChildByName(item, "icon");
    iconImg:loadTexture(getItemIconPath(ItemM.query(itemId, "icon")));

    -- 物品星级
    local starNode = findChildByName(item, "star_node");
    local rank = ItemM.query(itemId, "rank");
    local layer = createStarLayer(rank, "images/ui/symbol/star_little.png", "center", -0.7);
    if layer then
        starNode:removeAllChildren();
        starNode:addChild(layer);
    end

    -- 物品的背景框
    local frameImage = findChildByName(item, "bg");
    frameImage:loadTexture(getFrameBgIconPath("rank", 1));
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 尝试购买
function UIBuyScrap:tryBuy(amount)
    if "SkyPetShop" == self.priceType then
        local ret = SkyPetShopM.canBuyScrap(self.goodsId, amount);
        if ret then
            Operation.cmd_buy_sky_pet_scrap(self.goodsId, amount);
        end
    else
        local ret = MarketM.canBuySpecialGoods(self.goodsId, amount)
        if true ~= ret or type(ret) == "string" then
            if "sold_out" == ret then
                 -- 该商品已售完
                showHint(string.format(getLocStr("market_goods_sold_out"), MarketM.query(self.goodsId, "name")));
            elseif "gem_lack" == ret then
                -- 钻石不足
                showGemLackConfirm();
            elseif type(ret) == "string" then
                -- 有提示语，提示之
                showHint(getLocStr(ret));
            else
                -- 其他原因，统一提示失败
                trace("UIBuyScrap", "购买失败，原因：" .. tostring(ret))
                showHint(getLocStr("market_buy_fail"));
            end
        end

        -- 购买
        Operation.cmd_buy_special_goods(self.goodsId, amount);
    end
end

-- 倒计时
function UIBuyScrap:tickTime(itemId)
    if self.isTick then
        return;
    end

    self.isTick = true;

    local subHeadLabel = findChildByName(self.node, "CT/subhead");
    TextStyleM.setSubheadStyle(subHeadLabel);
    local dbase = MarketM.query(self.goodsId, "dbase") or {};

    local function tick()
        local remainTime = 0;
        if type(dbase["activity_id"]) == "table" then
            local activityId = ActivityDungeonM.getCurrentActivityId();
            if table.indexOf(dbase["activity_id"], activityId) >= 0 then
                remainTime = ActivityM.getRemainRunningTime(activityId);
            end
        else
            remainTime = ActivityM.getRemainRunningTime(dbase["activity_id"]);
        end
        local str = getLocStr("own_num");
        str = str .. string.format(getLocStr("activity_scrap_time"), remainingTimeDesc(remainTime));

        subHeadLabel:setString(string.format(str, ItemM.getAmount(ME.user, itemId)));
        if remainTime > 0 then
            performWithDelay(self.node, tick, 1);
        else
            -- 倒计时结束了
            UIMgr.getCurrentScene():removeFormByName("UIBuyScrap");
        end
    end

    performWithDelay(self.node, tick, 1);
end